<?php

namespace app\api\controller;
use app\admin\model\Article;
use app\admin\model\CouponRecord;
use app\admin\model\Order;
use app\api\service\SignService;
use app\common\controller\Api;
use app\common\model\Addresses;
use app\common\model\Pointsconfig;
use app\common\model\ScoreLog;
use app\common\model\ScoreOrder;
use app\common\model\ScoreProduct;
use app\common\model\SignIn;
use think\Cache;
use think\Db;

/**
 * 签到
 */
class Sign extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = '*';
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();

    }

    //签到
    public function signIn() {
        // 获取当前有效的签到奖励积分
        $signInBonus = Pointsconfig::getCurrentSignInBonus();

        $count = Db::name('sign_in_records')->where(['user_id' => $this->auth->id, 'sign_in_date' => date('Y-m-d')])->count();
        if ($count > 0) {
            return json(['code' => 1, 'msg' => '今日已签到','sign'=>1]);
        } else {
            Db::startTrans();
            try {
                // 记录签到
                Db::name('sign_in_records')->insert([
                    'user_id' => $this->auth->id,
                    'sign_in_date' => date('Y-m-d'),
                    'points_awarded' => $signInBonus
                ]);
                \app\common\model\User::score($signInBonus,$this->auth->id,'每日签到');

                Db::commit();
                return json(['code' => 1, 'msg' => '今日签到成功,获得指定妖币','sign'=>0]);
            } catch (\Exception $e) {
                Db::rollback();
                if ($e->getCode() === '23000') {
                    return json(['code' => 1, 'msg' => '今日已签到','sign'=>1]);
                } else {
                    return json(['code' => 1, 'msg' => $e->getMessage(),'sign'=>1]);
                }
            }
        }
    }


    //一周签到情况
    public function getThisWeekSignInStatus()
    {
        $userId = $this->auth->id;
        $startOfWeek = date('Y-m-d', strtotime('monday this week'));
        $endOfWeek = date('Y-m-d', strtotime('sunday this week'));
        // 获取本周的所有日期
        $dateRange = [];
        for ($date = strtotime($startOfWeek); $date <= strtotime($endOfWeek); $date = strtotime("+1 day", $date)) {
            $dateRange[] = date('Y-m-d', $date);
        }
        // 查询本周的签到记录
        $signInRecords = Db::table('fa_sign_in_records')
            ->where('user_id', $userId)
            ->whereIn('sign_in_date', $dateRange)
            ->column('sign_in_date, points_awarded', 'sign_in_date'); // 保存签到日期和对应的积分
        // 获取本周每一天的签到状态和相应积分
        $weekStatus = [];
        foreach ($dateRange as $date) {

            $status = [
                'date' =>  date('m.d', strtotime($date)),
                'status' => isset($signInRecords[$date]) ? 1: 0,
                'points_awarded' => null
            ];
            if (isset($signInRecords[$date])) {
                // 已签到，显示相应的积分
                $status['points_awarded'] = $signInRecords[$date];
            } else {
                // 未签到的情况
                if ($date < date('Y-m-d')) { // 如果是过去的日期
                    // 查询该日期时的积分配置
                    $pointsConfig = PointsConfig::where('valid_from', '<=', $date)
                        ->order('valid_from', 'desc')
                        ->limit(1)
                        ->value('config_value');

                    // 显示配置的积分
                    $status['points_awarded'] = $pointsConfig !== null ? $pointsConfig : 0; // 如果没有配置返回0
                } elseif ($date >= date('Y-m-d')) { // 如果是今天或未来的日期
                    // 获取当前有效的积分配置
                    $currentPointsConfig = PointsConfig::where('valid_from', '<=', date('Y-m-d'))
                        ->order('valid_from', 'desc')
                        ->limit(1)
                        ->value('config_value', 0); // 默认值为0积分
                    // 显示当前配置的积分
                    $status['points_awarded'] = $currentPointsConfig;
                }
            }
            $weekStatus[] = $status;
        }
        return json(['code' => 1, 'msg' =>'请求成功','data'=>$weekStatus]);

    }

    /*
     * 获取妖币明细
     */
    public function score_log(){
        $list=ScoreLog::where('user_id','=',$this->auth->id)->field('id,score,memo,createtime,before,after')->order('id desc')->paginate(10);
        foreach ($list as $item) {
            $item->op=$item->before>$item->after?'':'+';
        }
        $this->success('请求成功', $list);
    }

    /*
     * 兑换商品列表
     */
    public function ScoreProducts(){
        $score=\app\admin\model\User::where('id','=',$this->auth->id)->value('score');
        $list=ScoreProduct::where('status',1)->field('id,product_name,image,price')->order('weigh desc')->paginate(10);

        foreach ($list as $item) {
            $item->is_buy=$score>=$item->price?1:0;
        }
        $this->success('请求成功', $list);
    }

    /*
     * 商品详情
     */
    public function products_info()
    {
        if (!$id = input('id/d')) {
            $this->error(__('请选择商品'));
        }
        $info = ScoreProduct::where('id', '=', $id)->field('id,product_name,image,carousel,rich_text,price,video_url,postage')->find();
        if($info){
            $imagesArray = explode(',', $info['carousel']);
            $resultArray = [];
            foreach ($imagesArray as $url) {
                $resultArray[] = ['image' => trim($url)]; // 使用 trim 去除多余的空格
            }
            $info['carousel'] = $resultArray;
            $info['video_url'] =  $info['video_url']==""?[]:explode(',', $info['video_url']);
        }
        $this->success('请求成功', $info);
    }

    /*
     * 兑换详情
     */
    public function exchange_info()
    {
        $info = Article::where('type', '=', 'exchange')->field('content,video_url')->find();
        if($info){
            $info['video_url']= $info['video_url']==""?[]:explode(',', $info['video_url']);
        }
        $this->success('请求成功', $info);
    }

    /*
     * 兑换商品
     */
    public function exchange(){
        if (!$goodid = input('goodid/d')) {
            $this->error(__('请选择商品'));
        }

        $data = input('post.');
        $cacheKey = 'submit_' . md5(serialize($data));
        // 检查缓存中是否存在该键名
            if (Cache::has($cacheKey)) {
                $this->error(__('您点的太快了'));
            }
        Cache::set($cacheKey, true, 3);
        $order_no = order_no();
        Db::startTrans();
        $user=\app\admin\model\User::where('id',$this->auth->id)->lock(true)->find();
        try {
            if($data['send_type']==0){
                $address = Addresses::where('id', '=', $data['adrid'])->find();
                if (!$address) {
                    fail('请选择地址');
                }
                $address=Addresses::where('id',$data['adrid'])->field('id,address,phone,name,is_default,sex,(select name from fa_area where fa_area.id=province_id) province,(select name from fa_area where fa_area.id=city_id) city,(select name from fa_area where fa_area.id=district_id) district')->find();

            }

            $products = ScoreProduct::where('id', '=', $goodid)->find();
            if($user['score']< $products['price']){
                fail('您的妖币不足');
            }
            $balance_used=0;
            $postage=0;
            //如果是快递有邮费的情况下
            if($products['postage']>0&&$data['send_type']==0){
                $postage=$products['postage'];
                $user_money=$user['money'];
                $balance_used = min($user_money, $postage); // 使用余额抵扣剩余金额
                $postage -= $balance_used; // 更新最后的剩余金额
                if($postage>0){
                    $pay_status=0;
                }else{
                    $pay_status=1;
                }

            }else{
                $pay_status=1;
            }
            $order = ScoreOrder::insertGetId([
                'user_id' => $this->auth->id,
                'order_no' => $order_no,
                'amount' => $products['price'],
                'goodid'=>$goodid,
                'goodname'=>$products['product_name'],
                'goodimage'=>$products['image'],
                'name'=>$data['send_type']==0?$address['name']:'',
                'phone'=>$data['send_type']==0?$address['phone']:'',
                'address'=>$data['send_type']==0?$address['province'].$address['city'].$address['district']. $address['address'] :'',
                'send_type'=>$data['send_type'],
                'createtime'=>time(),
                'pay_status'=>$pay_status,
                'pay_time'=>$pay_status==1?time():null,
                'postage'=>$products['postage'],
                'balance'=>$balance_used,
                'paid'=>$postage,
            ]);
            Db::commit();
            if($pay_status==1){
                \app\common\model\User::score(-$products['price'],$this->auth->id,'兑换商品');
                if($balance_used>0){
                    \app\common\model\User::money(-$balance_used, $this->auth->id, '兑换商品邮费');
                }
                return json(['code'=>1,'msg'=>'请求成功','data'=>['id'=>$order,'is_pay'=>0]]);
            } else {
                return json(['code'=>1,'msg'=>'请求成功','data'=>['id'=>$order,'is_pay'=>1]]);

            }


        }catch (\think\Exception\HttpResponseException $e) {
            Db::rollback();
            $data = $e->getResponse()->getData();
            fail($data['msg'] ?? $e->getMessage());
        } catch (\Exception $e) {
            Db::rollback();
            fail($e->getMessage());
        }

    }


    //订单支付
    public function Sign_payment()
    {
        if (!$id = input('id/d')) {
            $this->error('订单ID不能为空');
        }
        $order_no = order_no();
        $result=ScoreOrder::where('id','=',$id)->where('pay_status','=',0)->update(['order_no'=>$order_no]);
        if($result===0){
            $this->error('当前订单已支付');
        }
        $payment = SignService::Sign_Payment($id, $this->auth->id);
        $this->success('请求成功', [
            'payment' => $payment,
        ]);
    }


    /*
     * 服务协议
     */


    public function service_info()
    {
        $info = Article::where('type', '=', 'service')->field('content')->find();
        $this->success('请求成功', $info);
    }


    //订单列表
    public function order_list($type = null) {
        $query = ScoreOrder::where('user_id', $this->auth->id);

        // 如果 status 被提供且不为空，则添加条件
        if ($type != null&&$type != '') {
            $query->where('send_status', $type);
        }else{

        }

        $query->where('pay_status', '=',1);
        // 分页并返回结果
        $list= $query->field('id,order_no,send_status status,goodid,goodimage,goodname,amount,postage,num')->order('id desc')->paginate(10);
        foreach ($list as $item){
            $data[]=['goodimage'=>$item['goodimage'],'goodname'=>$item['goodname'],'total'=>$item['amount']-$item['postage'],'num'=>$item['num']];
            $item->item=$data;
            $item->status=$item->status+1;
        }
        $this->success('请求成功',$list);
    }


    public function order_info(){
        $info=ScoreOrder::where('id',input('id'))->field('createtime,pay_time,id,send_status status,address,order_no,pay_time,goodname,goodimage,message,express_name,express_no,send_time,amount,postage,num,name linkman,phone linkphone')->find();
        if($info){
            $data[]=['goodimage'=>$info['goodimage'],'goodname'=>$info['goodname'],'total'=>$info['amount']-$info['postage'],'num'=>$info['num']];
            $info['status']=$info['status']+1;
            $info['item']=$data;
            $info['total']=$info['amount']-$info['postage'];
            $info['createtime'] = date('Y-m-d H:i:s', $info['createtime']);
            $info['pay_time'] = date('Y-m-d H:i:s', $info['pay_time']);

        }
        $this->success('请求成功',$info);
    }

    /*
    * 取消订单
    */
    public function cancel_order(){
        $order=ScoreOrder::where('id',input('id'))->find();
        if(!$order){
            $this->error(__('订单不存在'));
        }
        if($order['send_status']!=0){
            $this->error(__('当前订单无法取消'));
        }
       ScoreOrder::where('id',input('id'))->update(['cancel_time'=>time(),'send_status'=>3]);
        $this->success('请求成功',[]);
    }

    /*
     * 确认收货
     */
    public function confirm_order(){
        $order=ScoreOrder::where('id',input('id'))->find();
        if(!$order){
            $this->error(__('订单不存在'));
        }
        if($order['send_status']!=2){
            $this->error(__('当前订单无法收货'));
        }
        ScoreOrder::where('id',input('id'))->update(['cancel_time'=>time(),'status'=>2]);
        $this->success('请求成功',[]);
    }

    //获取物流API
    public function express_info()
    {

        $order =ScoreOrder::where('id','=',input('id'))->find();
        if ($order['send_status'] !=1&&$order['send_status'] !=2) {
            return fail('该订单暂未发货');
        }
        $express_name= $order['express_name'];
        $expressno=$order['express_no'];

        $express_company = db::table('fa_express_company')->where('express_name' ,'like', $express_name)->find();
        //参数设置
        $key = 'BHlZXckO8334';                        //客户授权key
        $customer = '8A0E592210113AAB4DAB0C2E47C56ADF';                   //查询公司编号
        $param = array (
            'com' => $express_company['express_code'],          //快递公司编码
            'num' => $expressno,   //快递单号
            'phone' => $order['phone'],                //手机号
            'from' => '',                 //出发地城市
            'to' =>  $order['address'],                   //目的地城市
            'resultv2' => '1'             //开启行政区域解析
        );
        //请求参数
        $post_data = array();
        $post_data["customer"] = $customer;
        $post_data["param"] = json_encode($param);
        $sign = md5($post_data["param"].$key.$post_data["customer"]);
        $post_data["sign"] = strtoupper($sign);
        $url = 'http://poll.kuaidi100.com/poll/maptrack.do';    //实时查询请求地址
        $params = "";
        foreach ($post_data as $k=>$v) {
            $params .= "$k=".urlencode($v)."&";              //默认UTF-8编码格式
        }
        $post_data = substr($params, 0, -1);
        //发送post请求
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($ch);
        $data = json_decode($result);
        if (isset($data->status) && $data->status == 200) {
            $this->success('请求成功', $data);
        } else {
            $this->error($data->message);
        }

    }


    public function sign_status()
    {


        $SignIn = SignIn::where('user_id', '=', $this->auth->id)->where('sign_in_date', date("Y-m-d"))->find();
        if ($SignIn) {
            $this->success('已签到', ['sign_in'=>1]);
        } else {
            $this->success('未签到', ['sign_in'=>0]);
        }
    }

}
